<template>
  <div style="width: 500px">
    <el-input
        placeholder="请输入部门名称进行搜索..."
        prefix-icon="el-icon-search"
        v-model="searchName">
    </el-input>
    <el-tree
        class="filter-tree"
        :data="deps"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        ref="tree">
<!--      按钮添加-->
      <span class="custom-tree-node" slot-scope="{ node, data }" style="display: flex;justify-content: space-between;width: 100%">
        <span>{{ node.label }}</span>
        <span>
          <el-button
              type="primary"
              size="mini"
              class="depBtn"
              @click="() => showAddView(data)">
            添加
          </el-button>
          <el-button
              type="danger"
              size="mini"
              class="depBtn"
              @click="() => handleDelete(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
        title="添加部门"
        :visible.sync="dialogVisible"
        width="30%">
      <div>
        <div style="margin-bottom: 5px">
          <el-tag size="small">上级部门</el-tag>
          <span style="margin-left: 5px">{{parentName}}</span>
        </div>
        <div>
          <el-tag type="primary">部门名称</el-tag>
          <el-input size="mini" placeholder="请输入部门名称.." class="addView" v-model="dep.name"></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleAdd">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "DepMana",
  data() {
    return {
        deps:[],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
      searchName:'',
      dialogVisible:false,
      parentName:'',
      dep:{
        name:'',
        parentId:''
      }
    }
  },
  mounted() {
    this.initDeps();
  },
  watch: {
    searchName(val) {
      // val:为搜索的值
      // 会调用el-tree中的filter-node-method，并传值val
      this.$refs.tree.filter(val);
    }
  },
  methods: {

    /**
     *  将删除的数据从deps中移除
     * @param pDep 父级信息
     * @param deps  部门树形结构数据
     * @param id  删除的部门id
     */
    opsDeleteDepToDeps(pDep, deps, id) {
      for (let i = 0; i < deps.length; i++) {
          let dep = deps[i];
          if (dep.id === id) {
            // splice() 方法用于添加或删除数组中的元素。
            deps.splice(i,1)
            if (deps.length === 0) {
              pDep.isParent = false;
            }
          return;
          }else {
            this.opsDeleteDepToDeps(dep,dep.children,id);
          }
      }
    },

    handleDelete(node,data) {
      console.log(data);
      if (data.isParent === 1) {
        this.$message.error("父级部门删除失败");
      }else {
        this.$confirm('此操作将永久删除['+ data.name +']部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest('/system/basic/department/' + data.id).then(resp => {
            if (resp) {
              this.opsDeleteDepToDeps(null,this.deps,data.id);
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }

    },

    opsAddDepToDeps(depInfo,deps) {
      for (let i = 0; i < deps.length; i++) {
          let dep = deps[i];
          // 查询新添加的父级信息
          if (dep.id === depInfo.parentId) {
              // concat:将数据通过逗号连接起来。
              dep.children = dep.children.concat(depInfo);
              if (dep.children.length > 0) {
                dep.isParent = true;
              }
              return;
          }else {
              this.opsAddDepToDeps(depInfo,dep.children)
          }
      }
    },

    handleAdd() {
      if (this.dep.name) {
        this.postRequest("/system/basic/department/",this.dep).then(resp => {
          if (resp) {
            // 变化树形结构数组
            // resp.data.id:新添加的id
            this.opsAddDepToDeps(resp.data,this.deps);
            // this.initDeps();
            this.dialogVisible = false;
            this.dep.name='';
            this.dep.parentId = -1;
            this.parentName = '';
          }
        })
      }else {
        this.$message.error("请填写部门名称")
      }
    },

    /**
     *  显示添加部门弹窗
     */
    showAddView(dep) {
        this.dialogVisible = true;
        this.dep.parentId= dep.id;
        this.parentName = dep.name;
    },

    /**
     *  查看所有部门树形结构信息
     */
    initDeps() {
        this.getRequest("/system/basic/department/").then(res => {
          if (res) {
            this.deps = res;
          }
        })
    },

    /**
     * 从搜索框中获取val，并在树形结构中查到对应的值。
     * @param value 搜索值
     * @param data  部门树形结构数据
     * @returns {boolean}
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

  },
}
</script>

<style scoped>
    .depBtn {
      padding:2px;
    }
    .addView {
      width: 200px;
      margin-left: 5px;
    }
</style>